package com.neoCalf.neoNotify.config;

import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.support.RetryTemplate;


/**
 * @author 小牛
 * @version 1.0
 * @description transactionQueue
 * @date 2025/4/8 11:48
 */
@Configuration
public class RabbitConfig {

    // 队列声明增强版 (持久化+内存控制)
    @Bean("sendCheckCodeQueue")
    public Queue sendCheckCodeQueue() {
        return QueueBuilder.durable("sendCheckCodeQueue")
                .withArgument("x-max-length", 100000)  // 最大消息数量
                .withArgument("x-max-length-bytes", 104857600) // 100MB 容量限制
                .deadLetterExchange("dlx.exchange") // 死信交换器
                .build();
    }

    // 消息转换器（JSON序列化）
    @Bean
    public MessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    // 发送模板配置
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        template.setMessageConverter(jsonMessageConverter());
        template.setRetryTemplate(retryTemplate());
        return template;
    }

    // 重试策略
    private RetryTemplate retryTemplate() {
        return RetryTemplate.builder()
                .maxAttempts(3)
                .fixedBackoff(1000)
                .build();
    }

    // 监听容器工厂
    @Bean
    public SimpleRabbitListenerContainerFactory containerFactory(
            ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setConcurrentConsumers(5); // 并发消费者数
        factory.setMaxConcurrentConsumers(10); // 最大并发数
        factory.setPrefetchCount(50); // 每个消费者预取数量
        factory.setMessageConverter(jsonMessageConverter());
        return factory;
    }
}

